package com.example.my_topbar;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * Created by fengke on 2016/7/5 0005.
 */
public class TopBar extends RelativeLayout {

    private TextView tv;
    private String tvText;
    private float tvSize;

    private Button leftButton;
    private String leftText;
    private Drawable leftDrawable;

    private Button rightButton;
    private String rightText;
    private Drawable rightDrawable;

    private LayoutParams leftParams,rightParams,tvParams;

    public interface topBarClickListener{
        public void onLeftClick();
        public void onRightClick();
    }

    public topBarClickListener listener;

    public void setOnTopBarClickListener(topBarClickListener listener){
        this.listener = listener;
    }

    public TopBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.TopBar);

        tvText = ta.getString(R.styleable.TopBar_TitleText);
        tvSize = ta.getFloat(R.styleable.TopBar_TtileTextSize, 0);

        leftText = ta.getString(R.styleable.TopBar_LeftButtonText);
        leftDrawable = ta.getDrawable(R.styleable.TopBar_LeftButtonBackground);

        rightText = ta.getString(R.styleable.TopBar_TitleText);
        rightDrawable = ta.getDrawable(R.styleable.TopBar_RightButtonBackground);

        ta.recycle();

        tv = new TextView(context);
        leftButton = new Button(context);
        rightButton = new Button(context);

        tv.setText(tvText);
        tv.setTextSize(tvSize);

        leftButton.setText(leftText);
        leftButton.setBackground(leftDrawable);

        rightButton.setText(rightText);
        rightButton.setBackground(rightDrawable);

        leftParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        leftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT,TRUE);
        addView(leftButton);

        tvParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        tvParams.addRule(RelativeLayout.CENTER_IN_PARENT,TRUE);
        addView(tv);

        rightParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,TRUE);
        addView(rightButton);

        leftButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onLeftClick();
            }
        });

        leftButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onRightClick();
            }
        });
    }
}
